package com.tg.push.initialization

import android.content.Context
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import androidx.core.util.Consumer
import com.tg.appcommon.android.TGLog
import com.tange.base.toolkit.ProcessUtils
import com.tg.push.BasePusher
import com.tg.push.BuildConfig
import com.tg.push.PushManager
import java.lang.ref.WeakReference

/**
 * 消息推送的初始化逻辑封装.
 * 在登录成功后设置了 TGCore.configureAccount() 后，再调用
 *
 * 包括：
 *     1. pushId的本地创建
 *     2. 将pushId提交到后端
 *
 */
object MessagePush {

    const val TAG = "MessagePush_"

    private var initialized = false

    private var initializationStatusListener: WeakReference<Consumer<PushingConfiguration>>? = null

    private val mainHandler = Handler(Looper.getMainLooper())

    fun configureHuaweiPushImpl(impl: BasePusher) {
        PushManager.setHuaweiPushImpl(impl)
    }

    fun enableAliMessageDirectlyLaunch() {


    }

    fun notifyInitializationStatus(configuration: PushingConfiguration) {
        mainHandler.post {
            initializationStatusListener?.get()?.let {
                TGLog.i(TAG, "[notifyInitializationStatus] $configuration")
                it.accept(configuration)
            } ?: kotlin.run {
                TGLog.i(TAG, "[notifyInitializationStatus] callback empty")
            }
        }
    }

    fun requireBinding(context: Context, listener: Consumer<PushingConfiguration>) {

        TGLog.i(TAG, "[requireBinding] MESSAGE_PUSH_POM_VERSION_NAME = ${BuildConfig.MESSAGE_PUSH_POM_VERSION_NAME}")

        initializationStatusListener = WeakReference(listener)
        initializationStatusListener?.get()?.let {
            TGLog.i(TAG, "[initialize] callback = $it")
        }
        if (initialized) {
            TGLog.i(TAG, "[initialize] ready")
            val existingId = PushManager.managerService()?.deviceId ?: ""
            val existingChannel = PushManager.managerService()?.pushChannel ?: ""
            if (!TextUtils.isEmpty(existingId) && !TextUtils.isEmpty(existingChannel)) {
                TGLog.i(TAG, "[initialize] use existing : $existingChannel , $existingId")
                submitPushId(context.applicationContext,existingId)
                return
            }
        }

        if (!ProcessUtils.isMainProcess(context.applicationContext)) {
            TGLog.i(TAG, "[initialize] ignore non-main-process")
            return
        }

        TGLog.i(TAG, "[initialize] start ...")

        PushManager.setOnPushIdUpdateCallback {
            TGLog.i(TAG, "[initialize] on push id updated")
            submitPushId(context,it)
        }

        PushManager.initPush(context.applicationContext)

        initialized = true
    }

    private fun submitPushId(applicationContext: Context, pushId: String) {
        if (!ProcessUtils.isMainProcess(applicationContext)) {
            TGLog.i(TAG, "[submitPushId] ignore non-main-process")
            return
        }
        TGLog.i(TAG, "[submitPushId] submit to backend service ...")

        PushManager.updatePushID(pushId)
    }
}

data class PushingConfiguration(

    /** 是否成功 */
    val success: Boolean,

    /** 错误码和原因 */
    val message: String? = null,

    /** 渠道名 */
    val channel: String? = null,

    /** 推送ID */
    val id: String? = null

)